package com.moter.estest.controller.admin;

import com.moter.estest.entity.DocFromInfo;
import com.moter.estest.entity.vo.DocQueryVo;
import com.moter.estest.result.R;
import com.moter.estest.result.ResultCodeEnum;
import com.moter.estest.service.DocService;
import com.moter.estest.util.ExceptionUtils;
import com.moter.estest.util.MoterException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

@RestController
@CrossOrigin
@Slf4j
@RequestMapping("/admin/doc")
@Api("文档管理")
public class DocController {
    @Autowired
    private DocService docService;

    @PostMapping("upload")
    @ApiOperation("上传文档")
    public R upload(@ApiParam(value = "文档",required = true)
                    @RequestParam("file")MultipartFile file){
        try {
            InputStream inputStream = file.getInputStream();
            String originalFilename = file.getOriginalFilename();
            docService.uploadFile(inputStream,originalFilename);
            return R.ok().message(originalFilename+"\t上传成功");
        } catch (Exception e) {
            log.error(ExceptionUtils.getMessage(e));
            throw new MoterException(ResultCodeEnum.ES_DOC_UPLOAD_ERROR);
        }
    }
    @PostMapping("query")
    @ApiOperation("根据关键字分页查询文档")
    public R upload(@ApiParam("关键字")@RequestBody DocQueryVo queryVo){
        try {
            List<DocFromInfo> docFromInfos = docService.searchDocFromInfosByKeyword(queryVo.getPageNo(),queryVo.getPageSize(),queryVo.getKeyword());
            return R.ok().data("items",docFromInfos);
        } catch (Exception e) {
            log.error(ExceptionUtils.getMessage(e));
            throw new MoterException(ResultCodeEnum.ES_DOC_QUERY_ERROR);
        }
    }
}
